const express = require('express');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

const router = express.Router();
const DATA_FILE = path.join(__dirname, '../data/user_events.json');

// 1. 用户行为埋点上报
// 删除: router.post('/track', ...)

// 2. 实时统计报表（简单示例：统计页面访问量）
// 删除: router.get('/stats', ...)

// 3. 用户分群与画像（调用阿里通义千问DashScope API）
router.get('/segmentation', async (req, res) => {
  if (!process.env.DASHSCOPE_API_KEY) {
    console.error('DASHSCOPE_API_KEY 未配置');
    return res.status(500).json({ error: 'DASHSCOPE_API_KEY未配置' });
  }
  let events = [];
  if (fs.existsSync(DATA_FILE)) {
    const content = fs.readFileSync(DATA_FILE, 'utf-8');
    if (content.trim()) {
      events = JSON.parse(content);
    }
  }
  const prompt = `\n以下是部分用户行为数据，请帮我做用户分群，并简要说明每个群体的特征：\n${JSON.stringify(events.slice(-200))}`;
  try {
    console.log('调用 DashScope segmentation');
    const response = await axios.post(
      'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
      {
        model: 'qwen-turbo',
        input: { prompt }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + process.env.DASHSCOPE_API_KEY
        }
      }
    );
    const result = response.data.output?.text || '无分群结果';
    res.json({ result });
  } catch (e) {
    console.error('DashScope segmentation 调用失败', e.response?.status, e.response?.data || e.message);
    res.status(500).json({ error: e.response?.data?.message || e.message });
  }
});

router.post('/chat', async (req, res) => {
  const { question } = req.body;
  if (!question || !question.trim()) {
    return res.status(400).json({ error: '问题不能为空' });
  }
  if (!process.env.DASHSCOPE_API_KEY) {
    console.error('DASHSCOPE_API_KEY 未配置');
    return res.status(500).json({ error: 'DASHSCOPE_API_KEY未配置' });
  }
  try {
    console.log('调用 DashScope chat');
    const response = await axios.post(
      'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
      {
        model: 'qwen-turbo',
        input: { prompt: question }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + process.env.DASHSCOPE_API_KEY
        }
      }
    );
    const answer = response.data.output?.text || 'AI暂无回复';
    res.json({ answer });
  } catch (e) {
    console.error('DashScope chat 调用失败', e.response?.status, e.response?.data || e.message);
    res.status(500).json({ error: e.response?.data?.message || e.message });
  }
});

module.exports = router;